package com.gjxx.common.repository;

import com.gjxx.common.annotation.ClassScanner;
import com.gjxx.common.enums.IEnum;
import com.gjxx.common.utils.BaseEnumUtil;
import com.gjxx.common.utils.ClasspathPackageScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author zha
 * @date 2018/6/14
 */
public class EnumRepository extends BaseRepository {

    private static final Logger log = LoggerFactory.getLogger(EnumRepository.class);

    private static EnumRepository instance = null;

    public static synchronized EnumRepository getInstance() {

        if (instance == null) {
            instance = new EnumRepository();
        }
        return instance;
    }

    /**
     * 所有缓存key
     */
    private final String key_all = "all";


    @Override
    public String getCacheName() {
        return EnumRepository.class.getSimpleName();
    }


    //------------------------------------------cache------------------------------

    @SuppressWarnings( { "rawtypes", "unchecked" } )
    public Map<String,Object> selectAll(String[] paths) {

        String key = this.key_all;

        Map<String,Object> result = (Map<String,Object>)super.getCacheValue(key);

        if (result != null) {
            log.debug("++ find enum from cache for key = " + key);
            return result;
        }
        log.debug("-- not find enum from cache for key = " + key);


        result = new HashMap<>(16);

        ClasspathPackageScanner scanner = new ClasspathPackageScanner(paths,ClassScanner.class);
        try {
            for ( Class<?> clazz : scanner.getClasses() ) {
                if (IEnum.class.isAssignableFrom(clazz) && !IEnum.class.equals(clazz)) {
                    ClassScanner className = clazz.getAnnotation(ClassScanner.class);
                    result.put(className.value(), BaseEnumUtil.getSerializes((Class<? extends IEnum>) clazz));
                }
            }
        } catch (ClassNotFoundException | IOException e) {

            e.printStackTrace();
        }



        this.setCacheValue(key, result);
        return result;

    }

    //------------------------------------------remove------------------------------

    public void removeAll() {
        String key = this.key_all;
        log.debug("** remove key from cache for key = " + key);
        super.removeCachedValue(key);
    }

}
